<template>
  <ToolboxWindow
    title="流量提醒设置"
    :show="show"
    :width="350"
    @close="show = false"
  >
    <div v-if="limits.length > 0">
      <el-form size="small">
        <el-form-item>
          <el-select
            v-model="selected"
            placeholder="Select"
            style="width: 240px"
            @change="handleSelect"
            :disabled="isContentChanged"
          >
            <el-option
              v-for="(item, index) in limits"
              :key="'limit' + index"
              :label="item.remark"
              :value="index"
            />
          </el-select>
          <span style="padding: 0 6px"></span>
          <el-button :disabled="isContentChanged" @click="handleAdd">
            <span>添加</span>
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="content"
            style="
              width: 300px;
              font-family: Consolas, 'Courier New', Courier, monospace;
            "
            :autosize="{ minRows: 10, maxRows: 50 }"
            type="textarea"
            placeholder="Please input"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="saveLimits()"
            :disabled="!isContentChanged"
            >保存</el-button
          >
          <el-button @click="loadLimits()" :disabled="!isContentChanged"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </ToolboxWindow>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { ElNotification } from "element-plus";
import useFlowStore from "@/store/flow.js";
const flowStore = useFlowStore();
import ToolboxWindow from "@/components/ToolboxWindow/index.vue";

const emits = defineEmits(["update"]);
const selected = ref(0);
const limits = ref([]);
const show = ref(false);
const open = () => {
  show.value = !show.value;
  loadLimits();
};

const content = ref("");
const contentBackup = ref("");

const handleSelect = (index = -1) => {
  index > -1 ? (selected.value = index) : null;
  content.value = JSON.stringify(limits.value[selected.value], null, 2);
  contentBackup.value = content.value;
};

const handleAdd = () => {
  limits.value.push({
    entries: [],
    remark: "新建提醒项",
    limits: {
      half: {
        enabled: 1,
        warning: 0,
        danger: 0,
      },
      full: {
        enabled: 1,
        warning: 0,
        danger: 0,
      },
    },
  });
  handleSelect(limits.value.length - 1);
};

const isContentChanged = computed(() => content.value != contentBackup.value);

const loadLimits = () => {
  limits.value = JSON.parse(JSON.stringify(flowStore.flowLimits));
  selected.value = 0;
  handleSelect();
};

const saveLimits = () => {
  if (!validateJSON(content.value)) {
    ElNotification({
      title: "流量提醒",
      message: "输入的内容有误",
      type: "error",
    });
    return false;
  }
  limits.value[selected.value] = JSON.parse(content.value);
  flowStore.flowLimits = limits.value;
  axios
    .post("api/common_params.php", {
      method: "SET",
      keys: ["FLOW_LIMITS_TMA"],
      values: [limits.value],
    })
    .then((response) => {
      if (response.data[0]) {
        handleSelect();
        ElNotification({
          title: "流量提醒",
          message: "已保存",
          type: "success",
        });
        emits("update");
      } else {
        ElNotification({
          title: "流量提醒",
          message: "出错了！！！",
          type: "error",
        });
      }
    })
    .catch((error) => {
      console.error("FlowLimitsSetter", error);
    });
};

const validateJSON = (jsonString) => {
  try {
    JSON.parse(jsonString);
    return true; // JSON 格式正确
  } catch (error) {
    return false; // JSON 格式错误
  }
};
defineExpose({ open });
</script>
